package com.anecdote.ideaplugins.changesbar;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.search.scope.packageSet.*;
import org.jetbrains.annotations.*;

import java.util.Collections;
import java.util.List;

public class ChangesScopeProvider implements CustomScopesProvider
{

  public static final String SCOPE_NAME = "Active changelist";
  public static final NamedScope SCOPE = new NamedScope(SCOPE_NAME, new MyPackageSet());

  private final boolean _enabled;

  public ChangesScopeProvider(@NotNull final ChangesBarApplicationComponent applicationComponent)
  {
    _enabled = ChangesBarApplicationComponent.isAddChangelistScope();
  }

  @NotNull
  public List<NamedScope> getCustomScopes()
  {
    return isScopeEnabled() ? Collections.singletonList(SCOPE) : Collections.<NamedScope>emptyList();
  }

  protected boolean isScopeEnabled()
  {
    return _enabled;
  }

  protected static boolean isChangesScope(@Nullable final NamedScope scope)
  {
    if (scope != null) {
      final PackageSet packageSet = scope.getValue();
      return packageSet != null && packageSet instanceof MyPackageSet;
    }
    return false;
  }

  private static class MyPackageSet implements PackageSet
  {

    public boolean contains(final PsiFile file, final NamedScopesHolder holder)
    {
      final VirtualFile virtualFile = file.getVirtualFile();
      if (virtualFile == null) {
        return false;
      }
      final Project project = file.getProject();
      final ChangeListManager changeListManager = ChangeListManager.getInstance(project);
      final Change change = changeListManager.getChange(virtualFile);
      if (change != null) {
        final LocalChangeList changeList = changeListManager.getChangeList(change);
        return changeList != null && changeList.equals(changeListManager.getDefaultChangeList());
      } else {
        return false;
      }
    }

    public PackageSet createCopy()
    {
      return new MyPackageSet();
    }

    @NonNls
    public String getText()
    {
      return "myPackageSet";
    }

    public int getNodePriority()
    {
      return 0;
    }
  }
}
